package com.jysz.certificate.web.listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.hibernate.FlushMode;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.orm.hibernate3.SessionHolder;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.jysz.certificate.spring.SpringBeanManager;

public class ApplicationListener implements ServletContextListener {
	
	private final static Logger LOG = LoggerFactory.getLogger(ApplicationListener.class);

	private SessionFactory sessionFactory;
	private Session session;
	
	public void contextInitialized(ServletContextEvent evt) {
		LOG.info("ApplicationListener start...");
		
		ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(evt.getServletContext());
		SpringBeanManager.initContext(context);
		
		//exec db script;
		DBManagerInitializer initEngine = DBManagerInitializer.getInstance();
		initEngine.setContext(evt.getServletContext());
		initEngine.initialize(null);
		
		before();
		
		after();
		
		LOG.info("ApplicationListener end...");
	}
	
	private void before(){
		sessionFactory = (SessionFactory) SpringBeanManager.getBean("sessionFactory");
		session = sessionFactory.openSession();
		session.setFlushMode(FlushMode.MANUAL);
		if(!TransactionSynchronizationManager.hasResource(sessionFactory)) {
			TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(session));
		}
	}
	
	private void after(){
		if(session != null) {
			session.flush();
			TransactionSynchronizationManager.unbindResource(sessionFactory);
			SessionFactoryUtils.closeSession(session);
		}
	}
	
	public void contextDestroyed(ServletContextEvent evt) {

	}
}
